import 'dart:convert';

import 'package:base_lib/common/base/base_theme_state.dart';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:base_lib/utils/color_util.dart';
import 'package:base_lib/utils/log.dart';
import 'package:base_lib/utils/toast.dart';
import 'package:doctor_inquiry_lib/bus.dart';
import 'package:doctor_inquiry_lib/constant/constant.dart';
import 'package:doctor_inquiry_lib/repository/https.dart';
import 'package:doctor_inquiry_lib/repository/im_http.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorBean;
import 'entity/im_chat_list_entity.dart' as ChatListBean;
import 'entity/doctor_patient_entity.dart' as DoctorPatientBean;
import '../doctor_inquiry_componet.dart';
import '../inquiry_plugin.dart';

///聊天列表控件
class ChatListWidget extends StatefulWidget {
  @override
  _ChatListWidgetState createState() => _ChatListWidgetState();

  static doImLogin(String doctorID) async {
    var isLogin = await InquiryPlugin.getInstance().getIsLogin() ?? false;
    if (isLogin) {
      return;
    }

    var result = await IMHttp.getUserSign(doctorID);
    if (result.isSuccess) {
      SPUtil.putString(Constant.SP_USER_SIGN, result.data);
      InquiryPlugin.getInstance().login(doctorID, result.data);
    } else {
      ToastUtil.error(result.error.msg);
    }
  }
}

class _ChatListWidgetState extends BaseThemeState<ChatListWidget> {
  RefreshController _controller;

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return chatList.isNotEmpty
        ? SmartRefresher(
            controller: _controller,
            onRefresh: () {
              InquiryPlugin.getInstance().initChatList();
            },
            onLoading: () {
              InquiryPlugin.getInstance().getChatList();
            },
            enablePullUp: chatList.length >= InquiryPlugin.chatCount,
            child: ListView.separated(
                itemBuilder: (BuildContext context, int index) {
                  return conversationListViewBuilder(chatList[index], index);
                },
                separatorBuilder: (context, index) {
                  return Divider(
                    height: 10,
                    thickness: 10,
                    color: ColorUtil.color("#f6f6f6"),
                  );
                },
                itemCount: chatList.length),
          )
        : GestureDetector(
            onTap: () {
              InquiryPlugin.getInstance().initChatList();
            },
            child: buildPageEmpty(des: '点击刷新'),
          );
  }

  // 会话列表构建
  Widget conversationListViewBuilder(
      ChatListBean.ImChatListEntity item, int pos) {
    // FLog(json.encode(item));
    DoctorPatientBean.PatientDatum info;

    try {
      info = item.patientData ??
          _patientInfoList
              .firstWhere((element) => element.keyId == item.getLastMsg.userID);
      item.patientData = info;
    } catch (e) {
      print(e);
    }

    return GestureDetector(
        onTap: () {
          Routers.navigateTo(context, DoctorInquiryComponent.chatC2CPage,
              parameters: Parameters()
                ..putObj('chat', item)
                ..putObj('doctor', _userInfo));
        },
        child: Container(
          padding: EdgeInsets.all(16),
          color: Colors.white,
          child: Row(
            children: [
              ClipRRect(
                child: PlaceholderImage(
                  width: 50,
                  height: 50,
                  placeholder: '${Constant.ASSETS_IMG_CHAT}public_avatar.png',
                  imgUrl: info?.faceImage ?? '',
                ),
                borderRadius: BorderRadius.circular(25),
              ),
              Container(
                height: 20,
                width: 20,
                margin: EdgeInsets.only(left: 5, bottom: 20),
                decoration: BoxDecoration(
                    color:
                        item.unreadCount == 0 ? Colors.transparent : Colors.red,
                    borderRadius: BorderRadius.circular(10)),
                alignment: Alignment.center,
                child: Text(item.unreadCount == 0 ? '' : '${item.unreadCount}',
                    style: TextStyle(fontSize: 12, color: Colors.white)),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      info?.personName ?? '',
                      style: TextStyle(fontSize: 16, color: Colors.black),
                    ),
                    Text(item.getLastMsg?.desc ?? '')
                  ],
                ),
              ),
              Spacer(),
              Text(TimelineUtil.formatA(item.getLastMsg.timestamp))
            ],
          ),
        ));
  }

  DoctorBean.DoctorUser _userInfo;

  List<DoctorPatientBean.Datum> _dataSourceArray =
      List<DoctorPatientBean.Datum>();

  List<DoctorPatientBean.PatientDatum> _patientInfoList =
      List<DoctorPatientBean.PatientDatum>();

  List<ChatListBean.ImChatListEntity> chatList = [];

  @override
  void initState() {
    super.initState();

    InquiryPlugin.getInstance().initMethodCallHandler();

    _controller = RefreshController();
    initLocalConversationList();
    UserInfoCache.getInstance().get().then((value) {
      _userInfo = value;
      fetchRemoteConversationList();
    });

    chatList.addAll(InquiryPlugin.getInstance().chatList);
    if (chatList.isNotEmpty) {
      doRefresh();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    globalBus.off(InquiryPlugin.BUS_KEY_REFRESH_CHAT_LIST);
    super.dispose();
  }

  ///1. 初始化本地会话缓存
  initLocalConversationList() {
    globalBus.on(InquiryPlugin.BUS_KEY_REFRESH_CHAT_LIST, (arg) {
      FLog('刷新 本地会话 ');
      _controller.refreshCompleted();
      _controller.loadComplete();

      chatList
        ..clear()
        ..addAll(arg);

      if (_dataSourceArray.isEmpty) {
        fetchRemoteConversationList();
      } else {
        getPersonInfoByPersonID();
      }
    });
  }

  /// 通过personID获取患者信息
  getPersonInfoByPersonID() async {
    if (_dataSourceArray.isNotEmpty) {
      var patientIdList = _dataSourceArray.map((e) => e.personId);
      chatList.removeWhere(
          (chat) => !patientIdList.contains(chat.getLastMsg.userID));
    }

    String ids = '';
    chatList.forEach((element) {
      if (!_patientInfoList.any((pl) => pl.keyId == element.patientID))
        ids += "${element.patientID},";
    });

    if (ids.length < 5 && _patientInfoList.isNotEmpty) {
      doRefresh();
      return;
    }

    var result = await DoctorInquiryHttp.getPersonInfoByPersonIDList(
        ids.substring(0, ids.length - 1));
    if (result.isSuccess) {
      _patientInfoList.addAll(result.data);
      doRefresh();
    }
  }

  /// 获取医生所有的患者会话列表
  fetchRemoteConversationList() async {
    if (_userInfo?.keyID?.isEmpty ?? true) {
      return;
    }

    var result = await DoctorInquiryHttp.getTalksByDoctor(_userInfo.keyID);
    if (result.isSuccess) {
      _dataSourceArray = result.data;
    }
  }

  doRefresh() {
    setState(() {});
  }
}
